package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0") //申明这是一个dubbo服务
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserLikeApi userLikeApi;

    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        Query query=Query.query(Criteria.where("toUserId").is(toUserId));
        query.with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long toUserId, Integer pageNum, Integer pageSize) {
        PageRequest pageable=PageRequest.of(pageNum-1,pageSize,Sort.by(Sort.Order.desc("score")));

        Query query=Query.query(Criteria.where("toUserId").is(toUserId)).with(pageable);

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<>(0,pageNum,pageSize,recommendUserList);
    }

    @Override
    public Double queryScore(Long userId, Long toUserId) {
        Query query=Query.query(Criteria.where("userId").is(userId)
        .and("toUserId").is(toUserId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (ObjectUtil.isEmpty(recommendUser)){
            return  90d;
        }
        return recommendUser.getScore();
    }

    @Override
    public List<RecommendUser> queryCardList(Long userId, Integer count) {

        List<Long> userIds=new ArrayList<>();

        //喜欢列表的用户
        userIds.addAll(this.userLikeApi.queryLikeList(userId));
        //不喜欢列表的用户
        userIds.addAll(this.userLikeApi.queryNotLikeList(userId));


        Pageable pageable=PageRequest.of(0,count,Sort.by(Sort.Order.by("score")));


        Criteria criteria = Criteria.where("toUserId").is(userId);
        if(CollUtil.isNotEmpty(userIds))
        {
            criteria.andOperator(Criteria.where("userId").nin(userIds));
        }
        Query query=Query.query(criteria).with(pageable);
        List<RecommendUser> recommendUsers = this.mongoTemplate.find(query, RecommendUser.class);

        return recommendUsers;
    }
}
